package com.unionftech.crm_android.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.text.TextUtils
import android.transition.TransitionManager
import android.view.MotionEvent
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.launcher.ARouter
import com.unionftech.baselibrary.glide.loadImage
import com.unionftech.common.R.string
import com.unionftech.common.base.BaseActivity
import com.unionftech.common.base.IUpdate
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.common.common.bean.BannerPosition
import com.unionftech.common.common.bean.CountryInfo
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.router.service.ILoginService
import com.unionftech.common.utils.ActivityCollector
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.SpUtils
import com.unionftech.common.utils.Utils
import com.unionftech.content_login.service.LoginConstants
import com.unionftech.content_login.ui.login.UFLoginActivity
import com.unionftech.crm_android.R
import kotlin.math.abs

class UFLoginRegisterActivity : BaseActivity(), IUpdate {
    private val mIvBackground by lazy { mRootView.findViewById<ImageView>(R.id.iv_background) }
    private val mIvGoogleLogin by lazy { mRootView.findViewById<ImageView>(R.id.iv_google_login) }
    private val mTvOtherLoginTitle by lazy { mRootView.findViewById<TextView>(R.id.tv_other_login_title) }
    private val mLlOtherLoginContainer by lazy { mRootView.findViewById<LinearLayout>(R.id.ll_other_login_container) }
    private val mBtnLogin by lazy { mRootView.findViewById<Button>(R.id.btn_login) }
    private val mBtnSignUp by lazy { mRootView.findViewById<Button>(R.id.btn_sign_up) }
    private var xDown = 0f
    private var xMove = 0f
    private var yDown = 0f
    private var yMove = 0f
    private var isSwiping = false
    private var swipeBackEnabled = true
    private val swipeThreshold = 150 // 滑动阈值(px)
    private val excludedViews = mutableListOf<View>()

    @Autowired
    @JvmField
    var mLoginService: ILoginService? = null

    init {
        ARouter.getInstance().inject(this)
    }

    companion object {
        @JvmStatic
        fun startThis(context: Context) {
            val intent = Intent(context, UFLoginRegisterActivity::class.java)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun initLayout() = R.layout.activity_uflogin_register

    override fun initLanguageText() {
        super.initLanguageText()
        mTvOtherLoginTitle.text = DynamicResourceManager.getString(
            mContext, string.or_sign_with
        )
        mBtnLogin.text = DynamicResourceManager.getString(mContext, string.log_in)
        mBtnSignUp.text = DynamicResourceManager.getString(mContext, string.sign_up)
    }

    override fun statusBar() {
        fullScreen()
    }

    override fun setListener() {
        super.setListener()
        mIvGoogleLogin.setOnClickListener(this)
        mBtnLogin.setOnClickListener(this)
        mBtnSignUp.setOnClickListener(this)
    }

    override fun setView() {
        super.setView()
        addExcludedView(mBtnLogin)
        addExcludedView(mBtnSignUp)
        hideTitleBar()
        initBackImage()
        loadData()
    }

    private fun initBackImage() {
        mIvBackground.setImageResource(R.drawable.icon_splash_bg)
        GlobalInfoManager.getInstance().getBannerInfo(BannerPosition.LOGIN_REGISTER)?.also { list ->
            list.getOrNull(0)?.also { info ->
                mIvBackground.loadImage(info.imageUrl, R.drawable.icon_splash_bg)
            }
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                xDown = ev.rawX
                yDown = ev.rawY

                // 检查触摸点是否在可点击视图上
                isSwiping = swipeBackEnabled && !isTouchOnExcludedViews(ev)
            }

            MotionEvent.ACTION_MOVE -> {
                if (!isSwiping) return super.dispatchTouchEvent(ev)

                xMove = ev.rawX
                yMove = ev.rawY

                val xDiff = xMove - xDown
                val yDiff = abs(yMove - yDown)

                // 如果检测到垂直滑动，取消滑动返回
                if (yDiff > 20 && yDiff > xDiff) {
                    isSwiping = false
                    return super.dispatchTouchEvent(ev)
                }

                // 只有横向滑动超过阈值才拦截事件
                if (abs(xDiff) > 20) {
                    return true
                }
            }

            MotionEvent.ACTION_UP -> {
                if (isSwiping) {
                    val rtl = Utils.isRTL()
                    val distance = xMove - xDown
                    if (abs(distance) > swipeThreshold) {
                        if (!rtl) {
                            if (distance > 0) {
                                finishWithAnimation()
                            }
                        } else {
                            if (distance < 0) {
                                finishWithAnimation()
                            }
                        }
                    } else {
                        overridePendingTransition(R.anim.cancel_slide, 0)
                    }
                }
                isSwiping = false
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    private fun finishWithAnimation() {
        finish()
        overridePendingTransition(R.anim.previous_from_left, R.anim.current_to_right)
    }

    override fun finish() {
        super.finish()
        if (isSwiping) {
            overridePendingTransition(R.anim.previous_from_left, R.anim.current_to_right)
        }
    }


    private fun addExcludedView(view: View) {
        excludedViews.add(view)
    }

    private fun isTouchOnExcludedViews(event: MotionEvent): Boolean {
        val location = IntArray(2)
        for (view in excludedViews) {
            view.getLocationOnScreen(location)
            val rect = Rect(
                location[0],
                location[1],
                location[0] + view.width,
                location[1] + view.height
            )
            if (rect.contains(event.rawX.toInt(), event.rawY.toInt())) {
                return true
            }
        }
        return false
    }

    override fun loadData() {
        super.loadData()
        val countryInfo = GlobalInfoManager.getInstance().getCountryInfo()
        countryInfo?.also {
            setShowOtherLoginWay(it.code != LoginConstants.Constant.CHINA_CODE)
        }
        if (countryInfo == null) {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update()
        }
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.btn_sign_up -> {
                mLoginService?.also { service ->
                    //首先判断其登录方式
                    val loginWay = SpUtils.getInstance().getString(LoginConstants.Key.LOGIN_WAY)
                    if (TextUtils.isEmpty(loginWay) || loginWay == LoginConstants.Constant.LOGIN_BY_QUICK) {
                        if (service.prefetchMobileState()) {
                            service.gotoLogin()
                            return
                        }
                    }
                    service.gotoRegister()
                    ActivityCollector.finishActivity(UFIntroductionActivity::class.java)
                    finish()
                }
            }

            R.id.btn_login -> {
                mLoginService?.also { service ->
                    if (service.prefetchMobileState()) {
                        service.gotoLogin()
                        return
                    }
                    UFLoginActivity.startThis(mContext)
                    ActivityCollector.finishActivity(UFIntroductionActivity::class.java)
                    finish()
                }
            }

            R.id.iv_google_login -> {
                mLoginService?.gotoGoogleLogin()
            }
        }
    }

    override fun onUpdate(obj: Any?) {
        if (obj is CountryInfo) {
            setShowOtherLoginWay(obj.code != LoginConstants.Constant.CHINA_CODE)
        }
    }

    private fun setShowOtherLoginWay(show: Boolean) {
        // 开始过渡动画
        TransitionManager.beginDelayedTransition(mRootView)
        LogUtils.d("UFLoginRegisterActivity", "setShowOtherLoginWay  show-->$show")
        if (show) {
            mLlOtherLoginContainer.visibility = View.VISIBLE
        } else {
            mLlOtherLoginContainer.visibility = View.GONE
        }
    }

    override fun onDestroy() {
        GlobalInfoManager.getInstance().remove(this)
        super.onDestroy()
    }
}